package com.aaa.lockscreen.deviceadmin;

import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;

/**
 * create by water.yuan
 * on 2020-11-26
 */
public class DeviceAdminManager {

    private static Context sContext;
    private static DevicePolicyManager sMDevicePolicyManager;
    private static ComponentName sComponentName;

    public static void init(Context context) {
        sContext = context.getApplicationContext();
        // 获取设备管理服务
        sMDevicePolicyManager = (DevicePolicyManager) sContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
        // 需要激活的DeviceAdminReceiver组件
        sComponentName = new ComponentName(sContext, MyDeviceAdminReceiver.class);
    }

    // 判断该组件是否已经是DeviceAdmin
    public static boolean isActive() {
        return sMDevicePolicyManager.isAdminActive(sComponentName);
    }

    // startActivity 不行，startActivityForResult 才行
    public static Intent getDeviceAdminIntent() {
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, sComponentName);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "为了一键锁屏需要申请设备管理权限，请同意");
        return intent;
    }

    private static void startDeviceAdminActivity() {
        Intent intent = new Intent(sContext, DeviceAdminActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        sContext.startActivity(intent);
    }

    /**
     * 杀死应用后，点击小部件的情况，
     * 杀死应用后，添加或者修改小部件会通过广播拉活应用，
     */
    public static void lockScreen() {
        if (isActive()) {
            sMDevicePolicyManager.lockNow();
        } else {
            startDeviceAdminActivity();
        }
    }

    public static void setCameraDisabled(boolean disabled) {
        if (sMDevicePolicyManager != null) {
            sMDevicePolicyManager.setCameraDisabled(sComponentName, disabled);
        }
    }
}
